#!/bin/bash

set -x

# default to update source then build

TOP_DIR=$(pwd)
SRC_DIR=$TOP_DIR/lib_source
BD_DIR=$TOP_DIR/lib_build
BIN_DIR=$TOP_DIR/lib_bin

export PATH=$TOP_DIR/cross/bin:$TOP_DIR/lib_build:$PATH

VER_OPT=3.3

cmd=all64
if [ -n "$1" ] ; then
	cmd=$1
fi

# llvm call wrong strip on mingw binary, disable it
mkdir -p $TOP_DIR/lib_build
cat > $TOP_DIR/lib_build/strip << EOF
#!/bin/bash

exit 0

EOF
chmod +x $TOP_DIR/lib_build/strip

if [ "$cmd" == "all64" ] || [ "$cmd" == "all32" ] || [ "$cmd" == "update" ] ; then
	mkdir -p $SRC_DIR || exit 0
	cd $SRC_DIR
	if [ ! -d llvm-$VER_OPT.src ] ; then
		wget http://www.llvm.org/releases/$VER_OPT/llvm-$VER_OPT.src.tar.gz
		wget http://www.llvm.org/releases/$VER_OPT/cfe-$VER_OPT.src.tar.gz
		wget http://www.llvm.org/releases/$VER_OPT/compiler-rt-$VER_OPT.src.tar.gz
		tar xzf llvm-$VER_OPT.src.tar.gz
		tar xzf cfe-$VER_OPT.src.tar.gz
		mv cfe-$VER_OPT.src llvm-$VER_OPT.src/tools/clang
		tar xzf compiler-rt-$VER_OPT.src.tar.gz
		mv compiler-rt-$VER_OPT.src llvm-$VER_OPT.src/projects/compiler-rt
	fi
	cd ..
fi

if [ "$cmd" == "all64" ] || [ "$cmd" == "b64" ] || [ "$cmd" == "all32" ] || [ "$cmd" == "b32" ] ; then
	HOST_FLAG="--host=x86_64-w64-mingw32"
	if [ "$cmd" == "all32" ] || [ "$cmd" == "b32" ] ; then
		HOST_FLAG="--host=i686-w64-mingw32"
	fi
	rm -rf $BIN_DIR/llvm
	mkdir -p $BD_DIR
	cd $BD_DIR
	rm -rf bd_llvm
	mkdir bd_llvm
	cd bd_llvm
	patch -d $SRC_DIR/llvm-$VER_OPT.src -p0 < $TOP_DIR/patch/llvm-w64.patch
	$SRC_DIR/llvm-$VER_OPT.src/configure $HOST_FLAG --prefix=$BIN_DIR/llvm \
		--enable-optimized

#		--enable-debug-runtime --enable-debug-symbols

	make $MAKE_OPT
	make install
	patch -d $SRC_DIR/llvm-$VER_OPT.src -p0 -R < $TOP_DIR/patch/llvm-w64.patch

	cd ..
	cd ..
fi

rm $TOP_DIR/lib_build/strip

